const cloud = require('wx-server-sdk');
const rpcUtils = require('../utils/rpcUtils');

// 工具函数：生成唯一用户 ID
function generateUserId() {
  const now = new Date();
  const dateString = now.toISOString().replace(/[^0-9]/g, '').slice(0, 14); // YYYYMMDDHHmmSS
  const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 生成六位随机数字
  return "U" + dateString + randomNum; // 拼接结果
}

// 工具函数：处理用户地址（排序 & 格式化）
function processUserAddress(addressList) {
  return addressList
    .sort((a, b) => b.is_default - a.is_default) // 将默认地址排在最前面
    .map(address => ({
      addressId: address.address_id,
      contactName: address.contact_name,
      contactPhone: address.contact_phone,
      addressDesc: address.address_desc,
      addressCode: address.address_code,
      addressDetail: address.address_detail,
      isDefault: address.is_default,
    }));
}

// 查询用户信息
async function getUserInfo(openId) {
  const userRecord = await cloud.database().collection('user').where({
    out_user_id: openId,
  }).get();
  return userRecord.data.length > 0 ? userRecord.data[0] : null; // 返回用户信息或 null
}

// 创建新用户
async function createNewUser(openId) {
  const newUser = {
    user_id: generateUserId(), // 生成唯一的 user_id
    out_user_id: openId,
    role_type: ['user'], // 默认角色类型为 "user"
    ext_info: {
      address: [], // 初始地址为空
    },
    create_ts: new Date(), // 创建时间戳
  };

  await cloud.database().collection('user').add({
    data: newUser,
  });

  return newUser; // 返回新用户信息
}

// 获取配置数据（如school_list, tan_chuang, homeUIConfigs）
async function getConfigs(configNames,schoolCode) {
  const configsVo = {};
  
  // 分别处理不同类型的配置
  for (const configName of configNames) {
    let condition = { config_name: configName };
    
    // 对于 school_list 和 tan_chuang，忽略 schoolCode
    if (configName === 'school_list' || configName === 'tan_chuang') {
      const configRes = await cloud.database().collection('config').where(condition).get();
      if (configRes.data.length > 0) {
        configsVo[configName] = configRes.data[0];
      }
    } else {
      // 对于其他配置，根据 schoolCode 进行筛选
      if (!schoolCode || schoolCode === '') {
        // schoolCode 为假值，筛选 school_code 字段不存在或为空字符串的记录
        condition.school_code = cloud.database().command.or([
          cloud.database().command.eq(null),
          cloud.database().command.eq(''),
          cloud.database().command.eq(undefined)
        ]);
      } else {
        // schoolCode 不为空，筛选 school_code 等于 schoolCode 的记录
        condition.school_code = schoolCode;
      }
      
      const configRes = await cloud.database().collection('config').where(condition).get();
      if (configRes.data.length > 0) {
        configsVo[configName] = configRes.data[0];
      }
    }
  }
  
  return configsVo;
}

// 计算两点之间的距离（使用Haversine公式）
function calculateDistance(lat1, lon1, lat2, lon2) {
  const R = 6371; // 地球半径，单位km
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLon = (lon2 - lon1) * Math.PI / 180;
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  return R * c; // 返回距离，单位km
}

// 获取学校列表并匹配当前位置
async function getAvailableSchools(longitude, latitude) {
  const schoolRes = await cloud.database().collection('config').where({ config_name: 'school_list' }).get();
  const availableSchoolList = schoolRes.data[0]?.content || [];
  
  // 将经纬度转换为数字
  const userLng = parseFloat(longitude);
  const userLat = parseFloat(latitude);
  
  // 计算每个学校到用户的距离
  const schoolsWithDistance = availableSchoolList.map(school => ({
    addressDesc: school.address_name,
    addressCode: school.address_code,
    isDefault: school.is_default,
    matchCurPosition: false,
    distance: calculateDistance(
      userLat,
      userLng,
      parseFloat(school.latitude),
      parseFloat(school.longitude)
    )
  }));

  // 按距离排序
  schoolsWithDistance.sort((a, b) => a.distance - b.distance);

  // 如果用户位置有效（不是0,0），则匹配最近的学校
  if (userLng !== 0 && userLat !== 0) {
    const nearestSchool = schoolsWithDistance[0];
    if (nearestSchool) {
      nearestSchool.matchCurPosition = true;
    }
  } else {
    // 如果用户位置无效，则使用默认学校
    const defaultSchool = schoolsWithDistance.find(school => school.isDefault === true);
    if (defaultSchool) {
      defaultSchool.matchCurPosition = true;
    }
  }

  // 移除distance字段，只返回需要的学校信息
  return schoolsWithDistance.map(({ distance, ...school }) => school);
}

// 获取优惠券包信息
async function getCouponPackage(openId, userSchoolCode) {
  const couponConfigsRes = await cloud.database().collection('coupon_config').get();
  const couponConfigsForSchools = couponConfigsRes.data;

  const schoolCouponConfig = couponConfigsForSchools.find(config =>
    config.available_address.includes(userSchoolCode)
  );

  if (!schoolCouponConfig) {
    return null;
  }

  const couponPackageId = schoolCouponConfig.coupon_package_id;
  const couponPackageVersion = schoolCouponConfig.coupon_package_version;

  const userCouponRecords = await cloud.database().collection('coupon_record').where({
    out_user_id: openId,
    coupon_package_id: couponPackageId,
    coupon_package_version: couponPackageVersion,
  }).get();

  return {
    couponPackageId,
    couponPackageVersion,
    popupImgUrl: schoolCouponConfig.coupon_popup_img_url,
    hasClaimed: userCouponRecords.data.length > 0,
    couponItems: schoolCouponConfig.coupon_items.map(item => ({
      couponId: item.coupon_id,
      tips: item.tips,
      price: item.price,
    })),
  };
}

// 获取产品信息并处理砍价数据
async function getProducts(openId, currentAddressCode) {
  const [productRes, bargainRes, bargainDetailRes] = await Promise.all([
    cloud.database().collection('product').where({ available_address: currentAddressCode }).get(),
    cloud.database().collection('bargain_record').where({ out_user_id: openId }).get(),
    cloud.database().collection('bargain_detail').where({ out_user_id: openId }).get(),
  ]);

  const products = productRes.data.map(product => ({
    productId: product.product_id,
    productTitle: product.product_title,
    productDesc: product.product_desc,
    imageUrl: product.image_url,
    price: product.price,
    status: product.status,
    index: product.index,
  }));

  for (let product of products) {
    const bargainRecord = bargainRes.data.find(bargain => 
      bargain.product_id === product.productId &&
      bargain.status === 'progressing' &&
      bargain.deadline &&
      bargain.deadline.getTime() > new Date().getTime()
    );

    if (bargainRecord) {
      product.totalAmount = bargainRecord.amount;
      product.isFriendToCut = true;
      product.participantId = bargainRecord.participant_id;

      const bargainDetails = bargainDetailRes.data.filter(detail => detail.participant_id === bargainRecord.participant_id);
      const bargainedAmount = bargainDetails.reduce((sum, detail) => sum + parseFloat(detail.help_price), 0);

      product.reducedAmount = bargainedAmount.toFixed(2);
      product.leftAmount = (parseFloat(bargainRecord.amount) - bargainedAmount).toFixed(2);
    } else {
      product.isFriendToCut = false;
    }
  }

  // 按索引排序
  products.sort((a, b) => a.index - b.index);

  return products;
}

// getHomeInfo主函数
async function getHomeInfo(getHomeInfoRequest) {
  const wxContext = cloud.getWXContext();
  const {longitude, latitude, configNames, schoolCode} = getHomeInfoRequest;

  const openId = wxContext.OPENID;

  try {
    // 1. 查询或注册用户
    let user = await getUserInfo(openId);
    if (!user) {
      user = await createNewUser(openId);
    }

    // 2. 先获取学校列表
    const schools = await getAvailableSchools(longitude, latitude);

    // 3. 确定当前学校代码
    let currentAddressCode = 'xue_chang_zhi_ye';
    if (schoolCode) {
      // 验证schoolCode是否在可用学校列表中
      const targetSchool = schools.find(school => school.addressCode === schoolCode);
      if (targetSchool) {
        // 更新所有学校的matchCurPosition状态
        schools.forEach(school => {
          school.matchCurPosition = school.addressCode === schoolCode;
        });
        currentAddressCode = schoolCode;
      } else {
        // 如果指定的schoolCode无效，使用匹配的学校
        currentAddressCode = schools.find(school => school.matchCurPosition === true)?.addressCode;
      }
    } else {
      currentAddressCode = schools.find(school => school.matchCurPosition === true)?.addressCode;
    }

    // 4. 使用确定的学校代码获取配置和其他数据
    const [configs, couponPackage, products] = await Promise.all([
      getConfigs(configNames, currentAddressCode),
      getCouponPackage(openId, currentAddressCode),
      getProducts(openId, currentAddressCode),
    ]);
   
    // 5. 返回统一结果
    return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS, "success", {
      userInfo: {
        openId: user.out_user_id,
        roleType: user.role_type,
        address: processUserAddress(user.ext_info.address),
      },
      configs,
      addressList: schools,
      couponPackage,
      products,
    });
  } catch (error) {
    console.error("Error:", error.stack || error);
    return rpcUtils.genResp(rpcUtils.codeEnum.ERROR, "Error processing request", null);
  }
}

// 获取产品列表（用于筛选）
async function getProductList(request) {
  try {
    console.log('getProductList 请求参数:', JSON.stringify(request));
    
    const { schoolCode } = request;
    
    // 使用传入的学校代码，如果没有则使用默认值
    const currentAddressCode = schoolCode || 'xue_chang_zhi_ye';
    console.log('使用的学校代码:', currentAddressCode);
    
    // 查询产品表
    console.log('开始查询产品表...');
    const productRes = await cloud.database().collection('product').where({ 
      available_address: currentAddressCode 
    }).get();
    
    console.log('查询结果:', JSON.stringify(productRes));
    console.log('查询到的产品数量:', productRes.data.length);

    if (!productRes.data || productRes.data.length === 0) {
      console.log('没有找到产品，返回空列表');
      return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS, "success", {
        products: []
      });
    }

    const products = productRes.data.map(product => {
      console.log('处理产品数据:', product.product_title, '产品ID:', product.product_id);
      return {
        productId: product.product_id,
        productTitle: product.product_title,
        productDesc: product.product_desc || '',
        imageUrl: product.image_url || '',
        status: product.status,
        index: product.index || 0,
      };
    });

    // 按索引排序
    products.sort((a, b) => (a.index || 0) - (b.index || 0));

    console.log('处理后的产品列表:', JSON.stringify(products));

    return rpcUtils.genResp(rpcUtils.codeEnum.SUCCESS, "success", {
      products
    });
  } catch (error) {
    console.error("getProductList Error:", error);
    console.error("Error stack:", error.stack);
    return rpcUtils.genResp(rpcUtils.codeEnum.ERROR, `获取产品列表失败: ${error.message}`, null);
  }
}

module.exports = {
  getHomeInfo,
  getProductList
}; 